<?php

/**
 * Zend Framework (http://framework.zend.com/)
 *
 * @link      http://github.com/zendframework/ZendSkeletonApplication for the canonical source repository
 * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd New BSD License
 */

namespace Member;

use Zend\Mvc\MvcEvent;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Member\Model\MemberModel;
use Member\Table\MemberTable;

class Module {

    public function onBootstrap(MvcEvent $e) {
        $eventManager = $e->getApplication()->getEventManager();
        // 注册一个事件
        $application = $e->getParam('application');
        $application->getEventManager()->attach('dispatch', array($this, 'setLayout'));
    }

    /**
     * @param  \Zend\Mvc\MvcEvent $mvcEvent The MvcEvent instance
     * @return void
     */
    public function setLayout($mvcEvent) {
        $matches = $mvcEvent->getRouteMatch();
        /**
         * @var \Zend\Mvc\Controller\AbstractActionController; $controller
         */
        $controller = $matches->getParam('controller');
        if (false === strpos($controller, __NAMESPACE__)) {
            // not a controller from this module
            return false;
        }
        // 自定义设置布局模板
        //针对 module.confi.php 下 template_map => layout 的设置
        $viewModel = $mvcEvent->getViewModel();
        if (!$viewModel->terminate()) {
            $viewModel->setTemplate('member/layout');
        };
    }

    public function getConfig() {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getAutoloaderConfig() {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    public function getServiceConfig() {
        return array(
            'factories' => array(
                'Member\Model\MemberTable' => function($sm) {
            $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
            $resultSetPrototype = new ResultSet();
            $resultSetPrototype->setArrayObjectPrototype(new MemberModel()); //当前应该是AccountAware 每个模块对应不同的 Aware
            $tableGateway = new TableGateway('admin', $dbAdapter, null, $resultSetPrototype); // TableGateway 定义 模型中的数据表
            $table = new MemberTable($tableGateway);
            return $table;
        }),
        );
    }

}
